package Network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class HomeworkUdpEchoClient {
    private DatagramSocket socket = null;

    private String serverIP;
    private int serverPort;

    public HomeworkUdpEchoClient(String serverIP,int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);


        while(true){
            // 1. 从控制台读取用户输入的内容
            System.out.println("请输入要发送的内容:");
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();

            //2.把请求发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);

            socket.send(requestPacket);

            //3. 接受响应并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            String response = new String(responsePacket.getData(),0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        HomeworkUdpEchoClient client = new HomeworkUdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
